package org.awenlice.playerdailyshop.event;

import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.awenlice.playerdailyshop.config.ShopConfig;
import org.awenlice.playerdailyshop.data.*;
import org.awenlice.playerdailyshop.gui.BuyShopGui;
import org.awenlice.playerdailyshop.gui.ShopGui;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Date;

@Mod.EventBusSubscriber
public class ShopRefreshHandler {

    @SubscribeEvent
    public static void onServerTick(TickEvent.ServerTickEvent event) {
        if (event.phase == TickEvent.Phase.END) {
            // 获取下次刷新时间
            ServerLevel level = event.getServer().overworld();
            CustomServerData data = CustomServerDataManager.get(level);

            long nextRefreshTime = data.getNextRefreshTime();
            long currentTime = System.currentTimeMillis(); // 当前时间（秒）

            if (nextRefreshTime == 0){
                LocalDateTime tomorrowStart = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                nextRefreshTime = tomorrowStart.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            }

            // 检查是否到达刷新时间
            if (currentTime - nextRefreshTime >= 0) {
                LocalDateTime tomorrowStart = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
                nextRefreshTime = tomorrowStart.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
                data.setNextRefreshTime(nextRefreshTime);

                // 刷新所有玩家的商店数据
                for (ServerPlayer player : event.getServer().getPlayerList().getPlayers()) {
                    // 重置出售商店数据
                    PlayerShopData sellShopData = PlayerShopDataManager.get(player);
                    sellShopData.setShopItems(ShopGui.generateShopItems());

                    // 重置收购商店数据
                    PlayerBuyShopData buyShopData = PlayerBuyShopDataManager.get(player);
                    buyShopData.setBuyShopItems(BuyShopGui.generateBuyShopItems());
                }

                System.out.println("已刷新所有玩家的商店数据！");
                System.out.println("当前为" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(currentTime)));
                System.out.println("下次刷新将在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(nextRefreshTime)));
            }
        }
    }
}